/**
 * @author yinghui.zhang  组织机构管理
 */
Ext.ns("cn.hls.web.action.dict");
var orgForm = cn.hls.web.action.dict.OrgForm;

orgForm = function () {
	var formPanel, win, grantmoduleTree, grantformPanel, grantwin;
	
	return {
		// ------------------------------------------------- formpanel & window
		createFormPanel : function() {
			formPanel =  new Ext.form.FormPanel( {
							id : 'formPanel',
							name : 'formPanel',
							labelAlign : 'right',
							labelWidth : 65,
							padding : "10",
							defaultType : 'textfield',
							defaults : {
									anchor : '90%'
							},
							items : [ {
								fieldLabel : '组织名称',
								id:'name',
								name : 'name',
								maxLength:32,
								allowBlank : false
							},{
								fieldLabel : '组织编码',
								id:'code',
								maxLength:32,
								name : 'code',
								allowBlank : false
							},
							{
							    fieldLabel : '上级机构',
								id:'parentresname',
								xtype : 'displayfield'
							},	
							 {
								id : 'fatherId',
								name : 'parent.id',
								hidden : true
							},
							{
								id : 'leader',name : 'leader',fieldLabel : '负责人',maxLength:32
							},
							{
								id : 'phone',name : 'phone',fieldLabel : '联系手机',maxLength:11,
								regex : /^(((13[0-9])|(15[^4,\D])|(18[0,5-9]))\d{8})$/,
								regexText:'格式错误'
							},
							 
							{
								id : 'windowmode',
								name : 'windowmode',
								hidden : true
							}, {
								id : 'id',
								name : 'id',
								hidden : true
							}, {
								id : 'sort',
								fieldLabel : '序号',
								xtype:'numberfield',
								name : 'sort',
								maxLength:5,
								regex: /^[1-9]*$/,
								regexText : '请输入正确的序号',
							},{
								fieldLabel : '说明',
								id:'remark',
								name : 'remark',
								maxLength:128,
								xtype:'textarea'
							}]
					});
			 return formPanel;
		},
		
		createWindow : function() {
			win =  new ExtWin({
						width : 420,
						height : 450,
						items : formPanel,
						buttons : [
							{
								text : '保存',
								iconCls : 'acceptIcon',
								handler : function() {
									var f = formPanel.getForm();
									if (f.isValid()){
										var mode = Ext.getCmp('windowmode').getValue();
										if (mode == 'add')
										{
										    orgView.subForm('/org/add.action');
										}
										else
										{
											orgView.subForm('/org/update.action');	
										}
									}
								}
							}, {
								text : '关闭',
								iconCls : 'deleteIcon',
								handler : function() {
									win.hide();
								}
							} ]
					});
			 return win;
		},
		
		// ------------------------------------------------- grant rights
		createGrantModuleTree : function(){
			grantmoduleTree = new Ext.tree.TreePanel( {
							loader : new Ext.tree.TreeLoader( {
								dataUrl :  cfg.cxt+'/module_tree.do',
								  listeners:{
					                beforeload:function(treeLoader, node){
					                    this.baseParams={  
					                        nodeId:node.attributes.id
					                    };
					                },
					                loadexception : bangni.storeLoadError
					            }
							}),
							root : new Ext.tree.AsyncTreeNode( {  
								text : '授权资源模块',
								expanded : true,
								id : '0'
							}),
							title : '',
							rootVisible: false,
							autoScroll : false,
							animate : false,
							useArrows : false, 
							border : false
			     	});
			  return grantmoduleTree;
		},
		
		setGrantModuleTreeClick : function() {
			grantmoduleTree.on('click', function(node) {
				Ext.getCmp('gtitle').setTitle('[ '+node.attributes.text+' ]授权信息')
				var g = Ext.getCmp('grantAll');
				if(g.disabled){
				    g.onDisableChange(false);
				    Ext.getCmp('canclegrantAll').onDisableChange(false);
				    Ext.getCmp('datagrant').eachItem(function(item){
						item.el.dom.disabled = false;
			        });
			        Ext.getCmp('aclstate').el.dom.disabled = false;
				}
				// 查询设置机构对应资源
				var moduleId  = node.attributes.id;
		        var param = 'principalType=Org&principalId={0}&moduleId='+moduleId;
		     	var rsp = orgView.editPermission( param , cfg.cxt+'/acl_searchAclRecord.do');
				var rs = Ext.decode(rsp);
				//系统权限
				if(rs[0].length == 0){
					    Ext.getCmp('datagrant').eachItem(function(item){
				             item.el.dom.checked = false;
				             item.checked = false; 
				        });
				        var f =  Ext.getCmp('aclstate');
				        f.checked  = false ;
						f.el.dom.checked = false;
				
				  } else {
						var r0 = rs[0];
						var i=1;
						var eb;
						var extState = false;
						Ext.getCmp('datagrant').eachItem(function(item){
							 var ga = r0[i] == 0 ? false : true;
							 if(!eb && ga) eb = true;
				             item.el.dom.checked = ga;
				             item.checked = ga; 
						     i++;
				        });
				        var f =  Ext.getCmp('aclstate');
				        if(eb){
				        	extState = r0[32] == 0 ? true : false ;
				        } else {
				            extState = false;//一个数据权限没选，即使数据库存在状态启用，这里设置不启用
				        }
				        f.checked  = extState ;
						f.el.dom.checked = extState;
				}
				//扩展权限
				var cext = Ext.getCmp('cext');
				if(cext.disabled){
					Ext.getCmp('cext').enable();
				}
				Ext.getDom('aclextform').reset();
				var r1 = rs[1];
				if(r1.length > 0){
					Ext.each(r1,function(r){
						Ext.getDom('acl_ext_name'+r.oprExt).value =  r.oprName;
					});
					
				} 
		   });
		},
		
		createGrantFormPanel : function() {
			grantformPanel = new Ext.form.FormPanel({
							labelAlign : 'left',
							labelWidth : 65,
							padding : "10",
							border: false,
							defaults : { anchor : '90%' },
							tbar:[ {
										text : '全选',
										iconCls : 'checkIcon',
										id : 'grantAll',
										disabled : true,
										handler : function() {
											var node  = grantmoduleTree.getSelectionModel().getSelectedNode();
									        var param = 'principalType=Org&principalId={0}&moduleId='+node.attributes.id+'&yes=true';
									     	var rsp = orgView.editPermission( param , cfg.cxt+'/acl_updateAll.do');
									     	var r =  Ext.decode(rsp);
											if(r.msg == "ok"){
												Ext.getCmp('datagrant').eachItem(function(item){
										             item.el.dom.checked = true;
										             item.checked = true; 
										        });
										        var f =  Ext.getCmp('aclstate');
										        f.checked  = true ;
												f.el.dom.checked = true;
												Ext.Mytip.msg('提示','授权成功！');
											}
										}
									},'-',{
										text : '取消全选',
										iconCls : 'remove',
										id : 'canclegrantAll',
										disabled : true,
										handler : function() {
											var ga;
											Ext.getCmp('datagrant').eachItem(function(item){
									             if(item.checked){
									                ga =  true;
									                return;
									             }
									        });
									        if(!ga){
									            Ext.Mytip.msg('提示','尚未选择任何数据权限！');
									        } else {
										     	var node  = grantmoduleTree.getSelectionModel().getSelectedNode();
										        var param = 'principalType=Org&principalId={0}&moduleId='+node.attributes.id+'&yes=false';
										     	var rsp = orgView.editPermission( param , cfg.cxt+'/acl_updateAll.do');
										     	var r =  Ext.decode(rsp);
												if(r.msg == "ok"){
													Ext.getCmp('datagrant').eachItem(function(item){
											             item.el.dom.checked = false;
											             item.checked = false; 
											        });
											        var f =  Ext.getCmp('aclstate');
											        f.checked  = false ;
													f.el.dom.checked = false;
													Ext.Mytip.msg('提示','取消授权成功！');
												}
									        }
											
										}
									}
							],
							items : [ { 
								    xtype:'fieldset',
								    title:'权限',
									collapsible : false,
									autoHeight:true,
									items:[{
											xtype : "checkboxgroup",
											fieldLabel : "数据权限",
											id : "datagrant",
											columns:4,
											items : [{
													id:'C',
													boxLabel : 'C',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(0,b);
														  }
												   }
												},{
													id:'R',
													boxLabel : 'R',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(4,b);	
														  }
												   }
												},{
												    id:'U',
													boxLabel : 'U',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(8,b);	
														  }
												   }
											   },{
												    id:'D',
													boxLabel : 'D',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(12,b);	
														  }
												   }
											   },{
												    id:'CA',
													boxLabel : 'CA',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(1,b);	
														  }
												   }
											   },{
												    id:'RA',
													boxLabel : 'RA',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(5,b);	
														  }
												   }
											   },{
												    id:'UA',
													boxLabel : 'UA',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(9,b);	
														  }
												   }
											   },{
												    id:'DA',
													boxLabel : 'DA',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(13,b);	
														  }
												   }
											   },{
												    id:'CD',
													boxLabel : 'CD',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(2,b);
														  }
												   }
											   },{
												    id:'RD',
													boxLabel : 'RD',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(6,b);	
														  }
												   }
											   },{
												    id:'UD',
													boxLabel : 'UD',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(10,b);	
														  }
												   }
											   },{
												    id:'DD',
													boxLabel : 'DD',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(14,b);	
														  }
												   }
											   },{
												    id:'CU',
													boxLabel : 'CU',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(3,b);
														  }
												   }
											   },{
												    id:'RU',
													boxLabel : 'RU',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(7,b);	
														  }
												   }
											   },{
												    id:'UU',
													boxLabel : 'UU',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(11,b);	
														  }
												   }
											   },{
												    id:'DU',
													boxLabel : 'DU',
													checked : false,
													listeners : {
														check : function(f, b) {
															orgView.editOnePermission(15,b);	
														 }
												   }
											   } ]
								       },{
											fieldLabel : "是否启用",
											xtype : "checkbox",
											boxLabel : "",
											id : "aclstate",
											checked : false,
											listeners : {
												check : function(f, b) {
											     	 var node  = grantmoduleTree.getSelectionModel().getSelectedNode();
											         var param = 'principalType=Org&principalId={0}&moduleId='+node.attributes.id+'&yes='+b;
											     	 orgView.editPermission( param , cfg.cxt+'/acl_updateEnable.do');
												  }
										   }
									}]
							 },{
								    xtype:'fieldset',
								    title:'权限说明',
									collapsible : false,
									autoHeight:true,
									items:[{
											fieldLabel : '&nbsp;&nbsp;&nbsp;&nbsp;C',
											xtype : 'displayfield',
											value :'所有创建权限'
									    },{
											fieldLabel : '&nbsp;&nbsp;CA',
											xtype : 'displayfield',
											value :'自己以及平级组织机构包括下级组织机构的创建权限'
									    },{
											fieldLabel : '&nbsp;&nbsp;CD',
											xtype : 'displayfield',
											value :'自己以及下级组织机构的创建权限 '
									    },{
											fieldLabel : '&nbsp;&nbsp;CU',
											xtype : 'displayfield',
											value :'只能操作自己的创建权限'
									    },{
											fieldLabel : '备注',
											xtype : 'displayfield',
											value :'R（查询）、U（修改）、D（删除）权限类似'
									    }]
								 
							 }]
			  });
			  return grantformPanel;
		},
		
		createGrantWin : function() {
			grantwin =  new ExtWin({
						layout : 'border',
						width : 700,
						height : 500,
						items : [{
							title : '所有资源',
							iconCls : 'layout_contentIcon',
							collapsible : true,
							width : 210,
							minSize : 160,
							maxSize : 280,
							split : true,
							region : 'west',
							autoScroll : true,
							items : [ grantmoduleTree ]
						}, {
							region : 'center',
							layout : 'fit',
							items : [ {
								 layout : 'fit',
								 border : false,
								 id : 'gtitle',
								 title :'请选择左侧树授权',
								 items : [new Ext.TabPanel({
								        activeTab:0,
								        id : 'tabPanel',
								        border : false,
								        enableTabScroll:true,
								        items: [{
								        	title : '系统权限',
								        	id :'csys',
								        	border : false,
								        	layout : 'fit',
								        	items : [grantformPanel]
								        },{
								        	title : '扩展权限',
								        	id :'cext',
								        	tbar : ['-',
												{
													text : '保存',
													iconCls : 'save',
												    handler : function() {
												    	var node  = grantmoduleTree.getSelectionModel().getSelectedNode();
												    	var ex = '';
												        for(var i=0;i<=15;i++){
												        	var x = Ext.getDom('acl_ext_name'+i).value.trim();
												        	if(x!='')
												        		ex += i+'|'+x+',';
												        }
												        var param = 'principalType=Org&principalId={0}&moduleId='+node.attributes.id+'&ex='+ex;
												        var rsp =  orgView.editPermission( param , cfg.cxt+'/acl_addOrUpdateExtPermission.do');
												     	var r =  Ext.decode(rsp);
												     	if(r.msg == "ok"){
												     		Ext.Mytip.msg('提示','操作成功！');
												     	}
												     	
												    	
													 }
												 },'-'
								        	],
								        	padding : "10",
											bodyStyle:'overflow-y:auto;overflow-x:hidden;',
											contentEl :'table_acl_ext_div'
								        }]
										
									}) ]
								} ]
						} ]
					});
			 return grantwin;		
		},
		
		setGrantWinOnShow : function() {
			grantwin.on('show',function(){
				grantmoduleTree.root.reload();
				Ext.getCmp('datagrant').eachItem(function(item){
		            if(item.checked){
		            	 item.el.dom.checked = false;
		            	 item.checked = false; //防止 item.checked 与  item.el.dom.checked 不一致导致 check事件无法触发
		            }
					item.el.dom.disabled = true;
		        });
		        var f =  Ext.getCmp('aclstate');
		        f.checked  = false;
				f.el.dom.checked = false;
				f.el.dom.disabled = true;
				Ext.getCmp('grantAll').onDisableChange(true);
				Ext.getCmp('canclegrantAll').onDisableChange(true);
				Ext.getCmp('gtitle').setTitle('请选择左侧树授权');
				Ext.getCmp('tabPanel').setActiveTab('csys');
				Ext.getCmp('cext').disable();
				if(Ext.getDom('table_acl_ext_div').style.display == 'none'){
					Ext.getDom('table_acl_ext_div').style.display = '';
				}
				Ext.getDom('aclextform').reset();
			});
		}
	}
	
}();